﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using eDocWS.Common;
using System.IO;

namespace eDocWS
{
    public partial class xml : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string folderPath = Server.MapPath(Utils.FolderPDF);
                DataTable dt = Utils.SetTableFile();
                string temp = "";
                string tempFileName = "";
                string tempCover = "";
               
                string[] arrTemp;
                foreach (string file in Utils.GetFiles(folderPath))
                {
                    DateTime dateCreated = File.GetCreationTimeUtc(file);
                    DateTime dateModify = File.GetLastWriteTimeUtc(file);                    
                    temp = file.Remove(0, folderPath.Length);
                    arrTemp = temp.Split("\\".ToCharArray());
                    tempFileName = arrTemp[arrTemp.Length - 1].ToString();
                    DataRow dr = dt.NewRow();
                    dr["PathFile"] = Utils.DomainFile + Utils.FolderPDF + temp.Replace("\\", "/");
                    dr["FileName"] = tempFileName.Remove(tempFileName.IndexOf("."));
                    dr["DateCreated"] = dateCreated;
                    dr["DateModify"] = dateModify;
                    tempCover = file.Replace(".pdf", ".png");
                    if (Utils.CheckFileExists(tempCover))
                    {
                        dr["Cover"] = Utils.DomainFile + Utils.FolderPDF + tempCover.Remove(0, folderPath.Length).Replace("\\", "/");
                    }
                    else
                    {
                        tempCover = tempCover.Replace(".png", ".jpg");
                        if (Utils.CheckFileExists(tempCover))
                        {
                            dr["Cover"] = Utils.DomainFile + Utils.FolderPDF + tempCover.Remove(0, folderPath.Length).Replace("\\", "/");
                        }
                        else
                        {
                            dr["Cover"] = "";
                        }
                    }
                    dt.Rows.Add(dr);
                }

                dt.AcceptChanges();

                DataView dv = dt.DefaultView;
                dv.Sort = "DateCreated desc, DateModify desc";
                DataTable sortedDT = dv.ToTable();

                grdPDF.DataSource = sortedDT;
                grdPDF.DataBind();
                Utils.CreateXml(sortedDT, Server.MapPath(Utils.FolderXML + "\\kiosk_list.xml"));
            }
        }
    }
}